<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>监室管理系统 - 用户管理</title>
    <link rel="stylesheet" href="/static/styles.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --background: #f8f9fa;
            --accent-color: #e74c3c;
            --success-color: #2ecc71;
        }

        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            margin: 0;
            padding: 0;
            display: block;
            background-color: var(--background);
            background-image: none; /* 移除背景图片 */
        }
        
        /* 导航栏样式 */
        .navbar {
            background-color: var(--primary-color);
            padding: 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .nav-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }

        .logo {
            color: white;
            font-size: 1.5em;
            font-weight: bold;
            padding: 15px 0;
            text-decoration: none;
        }

        .nav-links {
            display: flex;
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .nav-links li {
            margin: 0;
            padding: 0;
        }

        .nav-links a {
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            padding: 20px 15px;
            display: block;
            transition: all 0.3s;
            border-bottom: 3px solid transparent;
        }

        .nav-links a:hover, .nav-links a.active {
            color: white;
            border-bottom: 3px solid var(--secondary-color);
        }

        .user-controls {
            display: flex;
            align-items: center;
        }
        
        .user-management-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        .user-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            table-layout: fixed;
        }
        
        .user-table th,
        .user-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            word-wrap: break-word;
            word-break: break-all;
        }
        
        .user-table th:nth-child(1),
        .user-table td:nth-child(1) { width: 8%; }
        .user-table th:nth-child(2),
        .user-table td:nth-child(2) { width: 12%; }
        .user-table th:nth-child(3),
        .user-table td:nth-child(3) { width: 10%; }
        .user-table th:nth-child(4),
        .user-table td:nth-child(4) { width: 12%; }
        .user-table th:nth-child(5),
        .user-table td:nth-child(5) { width: 10%; }
        .user-table th:nth-child(6),
        .user-table td:nth-child(6) { width: 10%; }
        .user-table th:nth-child(7),
        .user-table td:nth-child(7) { width: 15%; }
        .user-table th:nth-child(8),
        .user-table td:nth-child(8) { width: 23%; }
        
        .user-table td.actions {
            text-align: center;
            white-space: nowrap;
            width: 1%;
        }
        
        .user-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        .user-table tr:hover {
            background-color: #f5f5f5;
        }
        
        .actions {
            white-space: nowrap;
            width: 1%;
            white-space: nowrap;
        }
        
        .actions .btn {
            width: 30%;
            min-width: 60px;
            margin: 2px;
        }
        
        .btn {
            padding: 8px 12px;
            margin: 2px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            max-width: 100%;
            box-sizing: border-box;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.8;
        }
        
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }
        
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 600px;
            border-radius: 5px;
            position: relative;
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            position: absolute;
            right: 15px;
            top: 10px;
        }
        
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .room-permissions {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            border-radius: 4px;
        }
        
        .floor-title {
            font-size: 18px;
            font-weight: bold;
            margin: 15px 0 10px 0;
            padding-bottom: 5px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .select-all-container {
            display: flex;
            align-items: center;
        }
        
        .select-all-label {
            margin-left: 5px;
            font-weight: normal;
            cursor: pointer;
        }
        
        .room-item {
            display: inline-block;
            padding: 8px 12px;
            margin: 5px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .room-item:hover {
            background-color: #e9ecef;
        }
        
        .room-item.selected {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        
        /* 楼层标题样式 */
        .floor-title {
            color: var(--secondary-color);
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
            margin: 20px 0 15px 0;
            font-size: 1.5em;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        /* 全选容器样式 */
        .select-all-container {
            display: flex;
            align-items: center;
        }
        
        /* 全选按钮样式 */
        .select-all-btn {
            margin-bottom: 10px;
            padding: 5px 10px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .select-all-btn:hover {
            background-color: #e0e0e0;
        }
        
        /* 楼层全选勾选框样式 */
        .floor-title input[type="checkbox"] {
            width: 18px;
            height: 18px;
            vertical-align: middle;
            margin-left: 15px;
            cursor: pointer;
        }
        
        /* 楼层全选勾选框样式 */
        .floor-title input[type="checkbox"] {
            width: 18px;
            height: 18px;
            vertical-align: middle;
            margin-left: 15px;
            cursor: pointer;
        }
        
        .floor-title label:not(.select-all-label) {
            vertical-align: middle;
            cursor: pointer;
            user-select: none;
        }
        
        /* 全选标签样式 */
        .select-all-label {
            margin-left: 8px;
            font-weight: normal;
            font-display:var(--primary-color);
            cursor: pointer;
            user-select: none;
            font-size: 1.1em;
            vertical-align: middle;
            display: inline-block;
            position: relative;
            z-index: 1;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="nav-container">
            <a href="/" class="logo">监室管理系统</a>
            <ul class="nav-links">
                <li><a href="/">首页</a></li>
                <li><a href="/rooms">房间管理</a></li>
                <li><a href="/profiles">人物画像</a></li>
                <li><a href="/medical">医疗辅助</a></li>
                <li><a href="/admin/users" class="active">用户管理</a></li>
            </ul>
            <div class="user-controls">
                {% if current_user.is_authenticated %}
                <span style="color: white; margin-right: 15px;">
                    欢迎，{{ current_user.username }}
                    {% if current_user.user_type != 'normal' %}
                    <span style="background: #f39c12; color: white; padding: 3px 8px; border-radius: 3px; font-size: 0.8em; margin-left: 5px;">管理员</span>
                    {% else %}
                    <span style="background: #3498db; color: white; padding: 3px 8px; border-radius: 3px; font-size: 0.8em; margin-left: 5px;">普通用户</span>
                    {% endif %}
                </span>
                <a href="/logout" style="background: var(--accent-color); color: white; padding: 8px 15px; border-radius: 5px; text-decoration: none;">
                    登出系统
                </a>
                {% else %}
                <a href="/login" style="background: var(--secondary-color); color: white; padding: 8px 15px; border-radius: 5px; text-decoration: none; margin-right: 10px;">
                    登录
                </a>
                <a href="/register" style="background: var(--success-color); color: white; padding: 8px 15px; border-radius: 5px; text-decoration: none;">
                    注册
                </a>
                {% endif %}
            </div>
        </div>
    </nav>
    
    <div class="user-management-container" id="app">
        <h1>用户管理</h1>
        
        <!-- 用户表格 -->
        <table class="user-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>姓名</th>
                    <th>电话</th>
                    <th>岗位</th>
                    <th>用户类型</th>
                    <th>房间权限</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="user in users" :key="user.id">
                    <td>${ user.id }</td>
                    <td>${ user.username }</td>
                    <td>${ user.full_name || '' }</td>
                    <td>${ user.phone || '' }</td>
                    <td>${ roleMap[user.role_id] || user.role_id || '' }</td>
                    <td>${ user.user_type === 'admin' ? '管理员' : '普通用户' }</td>
                    <td>
                        <span v-if="user.room_numbers && user.room_numbers.length > 0">
                            ${ formatRoomNumbers(user.room_numbers) }
                        </span>
                        <span v-else>无权限</span>
                    </td>
                    <td class="actions">
                        <button class="btn btn-primary" @click="showEditUser(user)">编辑信息</button>
                        <button class="btn btn-secondary" @click="showEditPermissions(user)">编辑权限</button>
                        <button class="btn btn-danger" @click="showDeleteConfirm(user)" :disabled="user.id == currentUserId">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        
        <!-- 移除了添加用户按钮 -->
        
        <!-- 移除了添加用户模态框 -->
        
        <!-- 编辑权限模态框 -->
        <div id="edit-permissions-modal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeEditPermissionsModal">&times;</span>
                <h2>编辑权限 - ${ editingUser.username }</h2>
                <div class="form-group">
                    <label>房间权限</label>
                    <div class="room-permissions">
                        <!-- 按楼层分组显示房间 -->
                        <div v-for="(rooms, floor) in groupedRooms" :key="floor">
                            <h3 class="floor-title">
                                第${ floor }层
                                <div class="select-all-container">
                                    <input type="checkbox" :id="'select-all-' + floor" @change="selectAllRooms(floor, $event)" :checked="areAllRoomsSelected(floor)">
                                    <label :for="'select-all-' + floor" class="select-all-label">全选${ floor }层房间</label>
                                </div>
                            </h3>
                            <div 
                                v-for="room in rooms" 
                                :key="room" 
                                class="room-item" 
                                :class="{ selected: editingUser.room_numbers.includes(room) }"
                                @click="toggleRoomSelection(room)"
                            >
                                ${ room }
                            </div>
                        </div>
                    </div>
                </div>
                <button class="btn btn-success" @click="updatePermissions">保存权限</button>
            </div>
        </div>
        
        <!-- 编辑用户信息模态框 -->
        <div id="edit-user-modal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeEditUserModal">&times;</span>
                <h2>编辑用户信息 - ${ editingUser.username }</h2>
                <div class="form-group">
                    <label>姓名</label>
                    <input type="text" v-model="editingUser.full_name" class="form-control">
                </div>
                <div class="form-group">
                    <label>电话</label>
                    <input type="text" v-model="editingUser.phone" class="form-control">
                </div>
                <div class="form-group">
                    <label>岗位</label>
                    <select v-model="editingUser.role_id" class="form-control">
                        <option value="">请选择岗位</option>
                        <option v-for="role in roles" :key="role.id" :value="role.id">${ role.name }</option>
                    </select>
                </div>
                <button class="btn btn-success" @click="updateUserInfo">保存信息</button>
            </div>
        </div>
        
        <!-- 删除确认模态框 -->
        <div id="delete-confirm-modal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeDeleteConfirmModal">&times;</span>
                <h2>确认删除</h2>
                <p>确定要删除用户 "${ userToDelete.username }" 吗？此操作不可撤销。</p>
                <div class="actions">
                    <button class="btn btn-danger" @click="deleteUser">确认删除</button>
                    <button class="btn" @click="closeDeleteConfirmModal">取消</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="{{ url_for('static', filename='lib/vue.js') }}"></script>
    <script>
        // Vue实例
        var userManagementApp = new Vue({
            el: '#app',
            delimiters: ['${', '}'],
            data: {
                users: [],
                allRooms: [],
                roles: [],
                currentUserId: {{ current_user.id }},
                newUser: {
                    username: '',
                    password: '',
                    user_type: 'normal'
                },
                editingUser: {
                    id: null,
                    username: '',
                    full_name: '',
                    phone: '',
                    role_id: '',
                    room_numbers: []
                },
                userToDelete: {
                    id: null,
                    username: ''
                }
            },
            computed: {
                // 按楼层分组房间
                groupedRooms: function() {
                    if (!this.allRooms || this.allRooms.length === 0) return {};
                    
                    const groups = {};
                    this.allRooms.forEach(room => {
                        // 假设房间号的第一位数字表示楼层
                        const floor = room.charAt(0);
                        if (!groups[floor]) {
                            groups[floor] = [];
                        }
                        groups[floor].push(room);
                    });
                    
                    // 按楼层号排序
                    const sortedGroups = {};
                    Object.keys(groups).sort().forEach(floor => {
                        sortedGroups[floor] = groups[floor];
                    });
                    
                    return sortedGroups;
                },
                
                // 角色ID到名称的映射
                roleMap: function() {
                    const map = {};
                    this.roles.forEach(role => {
                        map[role.id] = role.name;
                    });
                    return map;
                }
            },
            mounted: function() {
                this.loadUsers();
                this.loadRooms();
                this.loadRoles();
            },
            methods: {
                // 格式化房间号显示
                formatRoomNumbers: function(roomNumbers) {
                    if (!roomNumbers || roomNumbers.length === 0) return '无权限';
                    
                    // 如果房间数超过10个，只显示前10个并加"..."
                    if (roomNumbers.length > 10) {
                        return roomNumbers.slice(0, 10).join(', ') + '...';
                    }
                    return roomNumbers.join(', ');
                },
                
                // 加载用户数据
                loadUsers: function() {
                    fetch('/api/users')
                        .then(response => response.json())
                        .then(data => {
                            this.users = data;
                        })
                        .catch(error => {
                            console.error('加载用户数据失败:', error);
                            alert('加载用户数据失败');
                        });
                },
                
                // 加载房间数据
                loadRooms: function() {
                    fetch('/api/rooms')
                        .then(response => response.json())
                        .then(data => {
                            this.allRooms = data;
                        })
                        .catch(error => {
                            console.error('加载房间数据失败:', error);
                            alert('加载房间数据失败');
                        });
                },
                
                // 加载角色数据
                loadRoles: function() {
                    // 从模板中获取角色数据
                    const rolesData = [
                        { id: 1, name: '领导' },
                        { id: 2, name: '管教' },
                        { id: 3, name: '巡控' },
                        { id: 4, name: '窗口' },
                        { id: 5, name: '指中' }
                    ];
                    this.roles = rolesData;
                },
                
                // 显示添加用户模态框
                showAddUserModal: function() {
                    document.getElementById('add-user-modal').style.display = 'block';
                },
                
                // 关闭添加用户模态框
                closeAddUserModal: function() {
                    document.getElementById('add-user-modal').style.display = 'none';
                    this.resetNewUser();
                },
                
                // 重置新用户数据
                resetNewUser: function() {
                    this.newUser = {
                        username: '',
                        password: '',
                        user_type: 'normal'
                    };
                },
                
                // 添加用户
                addUser: function() {
                    // 发送添加用户请求
                    fetch('/admin/users', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            username: this.newUser.username,
                            password: this.newUser.password,
                            user_type: this.newUser.user_type
                        })
                    })
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            throw new Error('添加用户失败');
                        }
                    })
                    .then(data => {
                        if (data.success) {
                            alert('用户添加成功');
                            this.closeAddUserModal();
                            this.loadUsers(); // 重新加载用户数据
                        } else {
                            alert('用户添加失败: ' + data.error);
                        }
                    })
                    .catch(error => {
                        console.error('添加用户失败:', error);
                        alert('添加用户失败');
                    });
                },
                
                // 显示编辑用户信息模态框
                showEditUser: function(user) {
                    this.editingUser = {
                        id: user.id,
                        username: user.username,
                        full_name: user.full_name || '',
                        phone: user.phone || '',
                        role_id: user.role_id || '',
                        room_numbers: [...user.room_numbers] // 创建副本
                    };
                    document.getElementById('edit-user-modal').style.display = 'block';
                },
                
                // 关闭编辑用户信息模态框
                closeEditUserModal: function() {
                    document.getElementById('edit-user-modal').style.display = 'none';
                },
                
                // 更新用户信息
                updateUserInfo: function() {
                    const userId = this.editingUser.id;
                    const userData = {
                        full_name: this.editingUser.full_name,
                        phone: this.editingUser.phone,
                        role_id: this.editingUser.role_id
                    };
                    
                    fetch(`/admin/users/${userId}/info`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(userData)
                    })
                    .then(response => {
                        // 更详细地检查响应状态码
                        if (response.ok) {
                            return response.json();
                        } else {
                            // 获取响应文本以提供更详细的错误信息
                            return response.text().then(text => {
                                let errorMessage = '更新用户信息失败';
                                if (response.status === 500) {
                                    errorMessage = '服务器内部错误';
                                } else if (response.status === 400) {
                                    errorMessage = '请求参数错误';
                                } else if (response.status === 403) {
                                    errorMessage = '权限不足';
                                } else if (response.status === 404) {
                                    errorMessage = '用户不存在';
                                }
                                throw new Error(errorMessage + ': ' + text);
                            });
                        }
                    })
                    .then(data => {
                        if (data.success) {
                            alert('用户信息更新成功');
                            this.closeEditUserModal();
                            this.loadUsers(); // 重新加载用户数据
                        } else {
                            alert('用户信息更新失败: ' + data.error);
                        }
                    })
                    .catch(error => {
                        console.error('更新用户信息失败:', error);
                        alert('更新用户信息失败: ' + error.message);
                    });
                },
                
                // 显示编辑权限模态框
                showEditPermissions: function(user) {
                    this.editingUser = {
                        id: user.id,
                        username: user.username,
                        room_numbers: [...user.room_numbers] // 创建副本
                    };
                    document.getElementById('edit-permissions-modal').style.display = 'block';
                },
                
                // 关闭编辑权限模态框
                closeEditPermissionsModal: function() {
                    document.getElementById('edit-permissions-modal').style.display = 'none';
                },
                
                // 切换房间选择
                toggleRoomSelection: function(room) {
                    const index = this.editingUser.room_numbers.indexOf(room);
                    if (index > -1) {
                        // 已选择，移除
                        this.editingUser.room_numbers.splice(index, 1);
                    } else {
                        // 未选择，添加
                        this.editingUser.room_numbers.push(room);
                    }
                },
                
                // 全选某一层的房间
                selectAllRooms: function(floor, event) {
                    const roomsOnFloor = this.groupedRooms[floor] || [];
                    
                    if (event && event.target.checked) {
                        // 选中所有房间
                        roomsOnFloor.forEach(room => {
                            if (!this.editingUser.room_numbers.includes(room)) {
                                this.editingUser.room_numbers.push(room);
                            }
                        });
                    } else {
                        // 取消选中所有房间
                        this.editingUser.room_numbers = this.editingUser.room_numbers.filter(
                            room => !roomsOnFloor.includes(room)
                        );
                    }
                },
                
                // 检查某一层的所有房间是否都被选中
                areAllRoomsSelected: function(floor) {
                    const roomsOnFloor = this.groupedRooms[floor] || [];
                    if (roomsOnFloor.length === 0) return false;
                    
                    return roomsOnFloor.every(room => 
                        this.editingUser.room_numbers.includes(room)
                    );
                },
                
                // 更新权限
                updatePermissions: function() {
                    const userId = this.editingUser.id;
                    const roomNumbers = this.editingUser.room_numbers;
                    
                    fetch(`/admin/users/${userId}/permissions`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ room_numbers: roomNumbers })
                    })
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            throw new Error('更新权限失败');
                        }
                    })
                    .then(data => {
                        if (data.success) {
                            alert('权限更新成功');
                            this.closeEditPermissionsModal();
                            this.loadUsers(); // 重新加载用户数据
                        } else {
                            alert('权限更新失败: ' + data.error);
                        }
                    })
                    .catch(error => {
                        console.error('更新权限失败:', error);
                        alert('更新权限失败');
                    });
                },
                
                // 显示删除确认模态框
                showDeleteConfirm: function(user) {
                    this.userToDelete = {
                        id: user.id,
                        username: user.username
                    };
                    document.getElementById('delete-confirm-modal').style.display = 'block';
                },
                
                // 关闭删除确认模态框
                closeDeleteConfirmModal: function() {
                    document.getElementById('delete-confirm-modal').style.display = 'none';
                },
                
                // 删除用户
                deleteUser: function() {
                    const userId = this.userToDelete.id;
                    
                    fetch(`/admin/users/${userId}`, {
                        method: 'DELETE'
                    })
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            throw new Error('删除用户失败');
                        }
                    })
                    .then(data => {
                        if (data.success) {
                            alert('用户删除成功');
                            this.closeDeleteConfirmModal();
                            this.loadUsers(); // 重新加载用户数据
                        } else {
                            alert('用户删除失败: ' + data.error);
                        }
                    })
                    .catch(error => {
                        console.error('删除用户失败:', error);
                        alert('删除用户失败');
                    });
                }
            }
        });
    </script>
</body>
</html>